package com.brayan.webapp.controller.general.filters;

import java.io.IOException;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.brayan.webapp.controller.general.VisitController;

@Named
@SessionScoped
public class UriLoggingFilter implements Serializable, Filter {

	private static final long serialVersionUID = 1472782644963167647L;
	private static Logger LOGGER = Logger.getLogger(UriLoggingFilter.class);
	private String lastLoggedUri = "";

	FilterConfig filterConfig = null;
	@Inject
	VisitController visitController;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	/**
	 * Log requests of interest with the VisitController.
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,
			ServletException {

		// Run the other filters.
		filterChain.doFilter(request, response);

		if (request instanceof HttpServletRequest) {
			HttpServletRequest httpServletRequest = (HttpServletRequest) request;
			String queryString = httpServletRequest.getQueryString();
			String uri;
			if(queryString == null || queryString.isEmpty())
				uri = httpServletRequest.getRequestURI();
			else
				uri = httpServletRequest.getRequestURI() + "?" + queryString;
				

			String regex = "((/{1}\\w+$)|(/{1}\\w+\\.brayan$)|(/{1}\\w+\\.jsf\\?\\.*))";
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(uri);
			while (m.find()) {
				//LOGGER.info("match " + m.group());
				if (!lastLoggedUri.equals(uri)) {
					visitController.saveUriRequest(httpServletRequest);
					lastLoggedUri = uri;
				} else {
					LOGGER.warn("Multiple URI access to the same resource of the same user: " + uri);
				}
				break;
			}
		}
	}

	@Override
	public void destroy() {
		LOGGER.warn("Destroy filter");
	}
}
